package com.taotao.content.service.impl;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.content.redis.JedisClient;
import com.taotao.content.service.ContentService;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private JedisClient client;

    @Autowired
    private TbContentMapper tbContentMapper;

    @Value("${CONTENT_KEY}")
    private String CONTENT_KEY;

    @Override
    public List<TbContent> getContentListByCatId(Long catId) {
        //判断缓存有没有，如果有直接返回
        //redis缓存不能影响正常业务，所以要加上try catch
        try {
            String contentJson = client.hget(CONTENT_KEY, String.valueOf(catId));
            if (StringUtils.isNoneBlank(contentJson)) {
                System.out.println("从缓存中读取");
                return JsonUtils.jsonToList(contentJson, TbContent.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(catId);
        List<TbContent> contents = tbContentMapper.selectByExample(example);
        //将查询结果写入redis缓存中
        try {
            System.out.println("没有缓存");
            client.hset(CONTENT_KEY, String.valueOf(catId), JsonUtils.objectToJson(contents));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contents;
    }

    @Override
    public TaotaoResult saveContent(TbContent tbContent) {
        //补全其他信息
        tbContent.setCreated(new Date());
        tbContent.setUpdated(tbContent.getCreated());
        tbContentMapper.insertSelective(tbContent);
        //当插入内容时清空缓存
        try {
            client.hdel(CONTENT_KEY, String.valueOf(tbContent.getCategoryId()));
            System.out.println("清空缓存");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return TaotaoResult.ok(tbContent);
    }
}
